/**
 * Master Controller
 */

angular.module('NxtMap')
    .controller('MasterCtrl', ['$rootScope', '$scope', '$cookieStore', '$timeout', '$http', 'MapDiagram', 'MapAnalysis', 'MapService', 'ConstService', MasterCtrl]);

function MasterCtrl($rootScope, $scope, $cookieStore, $timeout, $http, MapDiagram, MapAnalysis, MapService, ConstService) {
   var month = new Date().getMonth() + 1 
  $rootScope.loop = 0;
  $rootScope.setShowMap(true);
  MapService.clearMap();
  MapService.clearRfidPonit();
  window.onresize = function() {
      $scope.$apply();
  };

  //timeline 配置
  $scope.showTimeaxis = function () {
    return $scope.items.length > 0;
  }
  $scope.items = [];
  $scope.selectedItem = {};
  $scope.checkItem = function (index) {
    $scope.selectedItem = $scope.items[index];
    draw();
  }
  //设置timeline内容
  function setTimeline(value) {
    $scope.items = [];
    $scope.selectedItem = {};
    if(value.length > 0){
      
      for(var i = 0; i < value.length; i++){
        var item = {index: i, itemId: value[i], content: value[i]};
        $scope.items.push(item);
      }

      if(value[0].indexOf('星期') > -1){
        $scope.items = [
          { index: 0, itemId: '星期0', content: '星期日' },
          { index: 1, itemId: '星期1', content: '星期一' },
          { index: 2, itemId: '星期2', content: '星期二' },
          { index: 3, itemId: '星期3', content: '星期三' },
          { index: 4, itemId: '星期4', content: '星期四' },
          { index: 5, itemId: '星期5', content: '星期五' },
          { index: 6, itemId: '星期6', content: '星期六' }
        ];
      }

      $scope.selectedItem = $scope.items[0];
      
    }
  };  

  //查询案件类型选项
  $scope.types = ConstService.types;  
  $scope.selectedTypes = [];
  $scope.selectedSubTypes = [];
  $scope.showType = -1;
  //类别多选框操作
  $scope.checkSubType = function (father, name){
    var index = $scope.selectedTypes.indexOf(father);
    if(index < 0){
      $scope.selectedTypes.push(father);
      $scope.selectedTypes[father] = [];
      $scope.selectedTypes[father].push(name);
    }
    else{
      var index1 = $scope.selectedTypes[father].indexOf(name);
      if(index1 < 0){
        $scope.selectedTypes[father].push(name);
      }
      else {
        $scope.selectedTypes[father].splice(index1, 1);
      }
    }
  }
  $scope.haveSubType = function (father, name){
    var index = $scope.selectedTypes.indexOf(father);
    if(index < 0){
      return false;
    }
    else {
      return $scope.selectedTypes[father].indexOf(name) > -1;
    }
  }
  $scope.checkShowType = function (typeIndex) {
    $scope.showType = $scope.showType == typeIndex ? -1 : typeIndex;
  }
  $scope.checkType = function (typeIndex, name) {
    var index = $scope.selectedTypes.indexOf(name);
    if(index < 0){
      $scope.selectedTypes.push(name);
      $scope.selectedTypes[name] = [];
      for(var i = 0; i < $scope.types[typeIndex].children.length; i++){
        var subName = $scope.types[typeIndex].children[i];
        // var subIndex = $scope.selectedSubTypes.indexOf(subName);
        // if(subIndex < 0){
        //   $scope.selectedSubTypes.push(subName);
        // }
        $scope.selectedTypes[name].push(subName);
      }
    }
    else{
      if($scope.selectedTypes[name].length == $scope.types[typeIndex].children.length) {
        $scope.selectedTypes.splice(index, 1);
        $scope.selectedTypes[name] = null;
      }
      else {
        for(var i = 0; i < $scope.types[typeIndex].children.length; i++){
          var subName = $scope.types[typeIndex].children[i];
          var subIndex = $scope.selectedTypes[name].indexOf(subName);
          if(subIndex < 0){
            $scope.selectedTypes[name].push(subName);
            // $scope.selectedSubTypes.splice(subIndex, 1);
          }
        }
        
      }
    }
    
  }
  $scope.haveType = function (name){
    return $scope.selectedTypes.indexOf(name) > -1;
  }
  $scope.havePart = function (typeIndex, name) {
    if($scope.selectedTypes.indexOf(name) < 0){
      return false;
    }
    else if($scope.selectedTypes[name].length == $scope.types[typeIndex].children.length) {
      return false;
    }
    return true;
  }


  //选项列表数据
  $scope.anaTypes = ConstService.anaTypes;
  $scope.hourList = ConstService.hourList;
  $scope.dateList = ConstService.dateList;
  $scope.timeList = ConstService.timeList;
  $scope.weekList = ConstService.weekList;
  $scope.stations = ['海宁公安局'].concat(ConstService.stations);

  //星期复选
  $scope.selectedWeek = ['1', '2', '3', '4', '5', '6', '7'];
  $scope.checkWeek = function (value) {
    var index = $scope.selectedWeek.indexOf(value);
    if(index < 0){
      $scope.selectedWeek.push(value);
    }
    else{
      $scope.selectedWeek.splice(index, 1);
    }
  }
  $scope.haveWeek = function (value) {
    return $scope.selectedWeek.indexOf(value) > -1;
  }

  //查询条件参数
  $scope.option = {
    number: 10,
    opacity: 5,
    size: 5,
    heightBase: 0,
    anaType: 'space',
    dateType: 'custom',
    startDate: new Date('2016/01/01'),
    endDate: new Date('2016/12/31'),
    hourType: '全天',
    startHour: '00',
    endHour: '23',
    station: '海宁公安局',
    spaceCell: 'square',
    timeCell: 'hour',
    showPoint: false
  };
  //计算后的地图数据
  $scope.computeData = {}; 
  //地图几何体数据 
  $scope.infoData = [];
  //原始数据
  $scope.originData = [];
  //图表数据
  $scope.dataMap = {};
  $scope.selectedMap = [];
  $scope.selectedStation = '';
  $scope.promiseList = null;
  $scope.infoIndex = -1;

  $scope.havePartMapName = function () {
    if(!$scope.dataMap.map) {
      return false;
    }
    return !($scope.selectedMap.length == $scope.dataMap.map.length) 
      && !($scope.selectedMap.length == 0);
  } 
  $scope.haveMapName = function (name) {
    if(!$scope.dataMap.map) {
      return false;
    }
    if(name == 'all') {
      return $scope.selectedMap.length == $scope.dataMap.map.length;
    }
    return $scope.selectedMap.indexOf(name) > -1;
  } 
  $scope.selectType = function (name) {
    if(name == 'all') {
      if($scope.selectedMap.length == $scope.dataMap.map.length) {
        $scope.selectedMap = [];
      }
      else {
        for(var i = 0; i < $scope.dataMap.map.length; i++) {
          if($scope.selectedMap.indexOf($scope.dataMap.map[i].name) < 0) {
            $scope.selectedMap.push($scope.dataMap.map[i].name);
          }
        }
      }
    }
    else {
      var indexM = $scope.selectedMap.indexOf(name);
      if(indexM < 0) {
        $scope.selectedMap.push(name);
      }
      else {
        $scope.selectedMap.splice(indexM, 1);
      }
    }
  }

  //切换地图
  $scope.mapType = 0;
  $scope.changeMap = function (value) {
    $scope.mapType = MapService.changeMap($scope.mapType, value);
  } 
  // $scope.changeMap(1);

  //刷新位置
  $scope.flyHome = function () {
    MapService.flyHome();
    // MapService.setPosition(120.55001, 30.43014, 0.15, - Math.PI / 2);
  }
  $scope.flyHome();

  // 添加实体的点击操作
  var scene = MapService.viewer.scene;
  // handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
  MapService.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
  MapService.handler.setInputAction(function(movement) {
    var pickedObject = scene.drillPick(movement.position);
    var checked = -1;
    if (Cesium.defined(pickedObject)) {
      for(var i = 0; i < pickedObject.length; i++){
        // MapService.viewer.zoomTo(pickedObject[i].id, new Cesium.HeadingPitchRange(0, - Math.PI / 2, 0));
        checked = pickedObject[i].id.name;
      }
    }
    if($scope.infoIndex != checked) {
      $scope.infoIndex = checked;
      if(checked < 0){
        $scope.dataMap = MapAnalysis.countType($scope.infoData.objects, $scope.qhour);
      }
      else {
        $scope.dataMap = MapAnalysis.countType($scope.infoData[checked].objects, $scope.qhour);
      }
      // MapDiagram.drawBar('chart1', dataMap);
      MapDiagram.drawLine('chart2', $scope.dataMap);

      //九宫格图
      $scope.nineMonthMap = {
        series:{},
        xAxis:[]
      }
       //当前月向前推12个月
      for(var i=0;i<12;i++){
        var val  = ''
        if(month+i<13){
          val = month+i+'';
        }else{
          val = month+i-12+'';
        }
        if(val.length==1){

          val = '0'+val;
        }
         $scope.nineMonthMap.xAxis.push(val)
      }
      var data = $scope.computeData.dataS[$scope.infoIndex].objects;
      //年内月统计
      var tj = [0,0,0,0,0,0,0,0,0,0,0,0]

      for(var j=0;j<data.length;j++){
        var bjsj = new Date(data[j].BJSJ).getMonth()+1;
        if(bjsj-month+1>0){
          tj[bjsj-month]++;
        }else{
          tj[bjsj-month+12]++;
        }
      }

      $scope.nineMonthMap.series['当前格'] = {
          color:'#4DBA7B',
          data:tj,
          name:'5'
      }
          $scope.clickNine(-1)
      MapDiagram.drawMultipleLine('chart3', $scope.nineMonthMap);
    }
    $scope.$apply();
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);


  $scope.details = [];
  $scope.showDetails = function (index) {
    $scope.details = $scope.infoData[index].objects;
    $scope.tparam = {
      total: $scope.infoData[index].objects.length,
      max: Math.ceil($scope.infoData[index].objects.length / 10),
      pages: [],
      now: 1
    }
    $scope.tparam.pages = generatePageNum($scope.tparam.now, $scope.tparam.max);
    $scope.showInfo = true;
  }
  $scope.goPage = function (value) {
    if(value == 'pre') {
      if($scope.tparam.now > 1) {
        $scope.tparam.now --;
      }
    }
    else if(value == 'next') {
      if($scope.tparam.now < $scope.tparam.max){
        $scope.tparam.now ++;
      }
    }
    else if(value == '···' || value == '··') {
      return;
    }
    else {
      $scope.tparam.now = value;
    }
    $scope.tparam.pages = generatePageNum($scope.tparam.now, $scope.tparam.max);
  }
  function generatePageNum(index, max) {
    var result = [];
    var num = 5;
    if(max < 8){
      var ii = 1;
      while (ii <= max) {
        result.push(ii);
        ii++;
      }
      return result;
    }
    var minv = index - 2, maxv = index + 2;
    if(minv <= 1) {
      maxv = 1 - minv + maxv;
      minv = 1;
    }
    else {
      result.push('··');
    }
    if(maxv >= max) {
      minv = minv - (maxv - max);
      maxv = max;     
    }
    for(var i = minv; i <= maxv; i++){
      result.push(i);
    }
    if(maxv < max) {
      if(maxv < max - 1){
        result.push('···');
      }
      result.push(max);
    }
    return result;
  }

  var url_origin = $rootScope.url_origin + '/jingqings';
  //图层调整变化监控
  //显示多边形切换
  $scope.$watch('option.spaceCell', function(newValue, oldValue) {
    if($scope.computeData.s != null){
      draw();
    }
  });
  $scope.$watch('option.timeCell', function(newValue, oldValue) {
    if($scope.originData.length > 0){
      var formatParam = judgeType($scope.option.anaType, newValue);
      $scope.computeData = MapAnalysis.compute($scope.originData, formatParam);
      setTimeline($scope.computeData.timelineList);
      draw();
    }
  });
  $scope.$watch('option.number', function(newValue, oldValue) {
    setCss('#number', newValue * 10);
    if($scope.promise || newValue != oldValue){
      $timeout.cancel($scope.promise);
      $scope.promise = $timeout(draw, 300);
    }
  });
  $scope.$watch('option.opacity', function(newValue, oldValue) {
    setCss('#opacity', newValue * 10);
    if($scope.promise || newValue != oldValue){
      $timeout.cancel($scope.promise);
      $scope.promise = $timeout(draw, 300);
    }
  });
  $scope.$watch('option.heightBase', function(newValue, oldValue) {
    setCss('#heightBase', newValue / 10);
    if($scope.promise || newValue != oldValue){
      $timeout.cancel($scope.promise);
      $scope.promise = $timeout(draw, 300);
    }
  });
    $http({
    method: 'POST',
    url: url_origin + '/countDept',
    data: {starttime:'2017-12-01',endtime:'2018-01-01'}
  }).success(function (result){
    $scope.xqData= result;
  });

  $scope.$watch('option.size', function(newValue, oldValue) {
    var percent = (newValue - 1) / 9 * 100;
    setCss('#size', percent);
    $http({
      method: 'POST',
      url: url_origin + '/set',
      data: {s: 0.001 * $scope.option.size}
    }).success(function (resp){
      console.log(resp);
      MapAnalysis.setS(0.001 * $scope.option.size);
    });
    if($scope.promise || newValue != oldValue){
      $timeout.cancel($scope.promise);
      $scope.promise = $timeout($scope.submit, 1000);
      
    }
  });
  $scope.$watch('option.showPoint', function(newValue, oldValue) {
    if($scope.originData.length > 0){
      draw();
    }
  })

  //提交查询，返回结果，进行分析，添加图层
  $scope.submit = function () {
    setCss('#number', $scope.option.number * 10);
    setCss('#heightBase', $scope.option.heightBase / 10);
    setCss('#size', ($scope.option.size - 1) / 9 * 100);
    if($scope.selectedTypes.length > 0) {
      var qdate = getDate($scope.option.dateType);
      $scope.qhour = getHour($scope.option.hourType);

      var type = '';
      var subType = '';
      for(var i = 0; i < $scope.selectedTypes.length; i++){
        var name = $scope.selectedTypes[i];
        type = type + '"' + name + '",';
        for(var j = 0; j < $scope.selectedTypes[name].length; j++){
          subType = subType + '"' + $scope.selectedTypes[name][j] + '",';
        }
      }


      var station_str = '';
      $scope.selectedStation = $scope.option.station;
      if($scope.option.station != '海宁公安局') {
        station_str = ' , "bumen": "' + $scope.option.station + '"';
      }

      var url_path = '?filter={"where": {"BJSJ": {"between": ["' 
        + qdate[0] + '", "' 
        + qdate[1]
        + '"]}, "XS": {"between": ["' 
        + $scope.qhour[0] + '", "' 
        + $scope.qhour[1]
        + '"]}, "XQ": {"inq": [' 
        + $scope.selectedWeek.toString()
        + ']}, "BJLBMC": {"inq": ['        
        + type.substring(0, type.length - 1)
        + ']}, "BJXLMC": {"inq": [' 
        + subType.substring(0, subType.length - 1)
        + ']}' + station_str + '}}';

      console.log(url_path);
      
      $http.get(url_origin + url_path).success(function (data) {
        console.log(123,data)
        $scope.originData = data;
        var formatParam = judgeType($scope.option.anaType, $scope.option.timeCell);
        $scope.computeData = MapAnalysis.compute(data, formatParam);
        console.log($scope.computeData)
        setTimeline($scope.computeData.timelineList);
        draw();
        $scope.isSummaryFold = false;
      });
      $scope.isSelectorFold = true;
    }
  }

  $scope.checkType(1, '刑事案件');
  $scope.submit();

  var draw = function draw() {
    var param = {
      colorIndex: 8,
      timeline: $scope.selectedItem.itemId,
      heightBase: $scope.option.heightBase,
      opacity: $scope.option.opacity / 10,
      lenPercent: $scope.option.number / 10
    }
    $scope.infoData = MapService.drawMap($scope.option.spaceCell,
      $scope.originData, $scope.computeData, param);
    $scope.infoIndex = -1;
    $scope.dataMap = MapAnalysis.countType($scope.infoData.objects, $scope.qhour);
    // MapDiagram.drawBar('chart1', dataMap);
    MapDiagram.drawLine('chart2', $scope.dataMap);
/*       MapDiagram.drawLine('chart3', $scope.dataMap);*/
    if($scope.option.showPoint){
      MapService.drawPointGeometry($scope.originData);
    }
  }

  function judgeType(anaType, timeCell) {
    var formatParam = null;
    if(anaType == 'timeSpace') {
      switch (timeCell){
        case 'hour': 
          formatParam = 'HH';
          break;
        case 'week': 
          formatParam = '星期w';
          break;
        case 'month': 
          formatParam = 'MM月';
          break;
        case 'year': 
          formatParam = 'yyyy年';
          break;
      }
    }
    else if(anaType == 'timeOrder'){
      switch (timeCell){
        case 'week': 
          formatParam = 'yyyy年MM月w';
          break;
        case 'month': 
          formatParam = 'yyyy年MM月';
          break;
        case 'year': 
          formatParam = 'yyyy年';
          break;
      }
    }
    return formatParam;
  }

  function getDate(dateType) {
    var start = new Date();
    var end = new Date();
    switch (dateType){
      case 'yesterday':
        start.setDate(start.getDate() - 1);
        end.setDate(end.getDate() + 1);
        break;
      case 'lastweek':
        start.setDate(start.getDate() - start.getDay() - 7);
        end.setDate(end.getDate() - end.getDay());
        break;
      case 'lastmonth':
        start.setDate(1);
        start.setMonth(start.getMonth() - 1);
        end.setDate(1);
        break;
      case 'thisweek':
        start.setDate(start.getDate() - start.getDay());
        end.setDate(end.getDate() + 1);
        break;
      case 'thismonth':
        start.setDate(1);
        end.setDate(end.getDate() + 1);
        break;
      case 'custom':
        start = $scope.option.startDate;
        end = $scope.option.endDate;
        // end.setDate(end.getDate() + 1);
        break;
    }
    return [start.format('yyyy/MM/dd'), end.format('yyyy/MM/dd')];
  }

  function getHour(hourType) {
    if(hourType == '自选时间') {
      return [$scope.option.startHour, $scope.option.endHour]; 
    }
    for(var i = 0; i < $scope.timeList.length; i++){
      if(hourType == $scope.timeList[i].name) {
        return [$scope.timeList[i].start, $scope.timeList[i].end];
      }
    }
  }

  function setCss(elementId, value){
    $(elementId).attr('style','background:-webkit-linear-gradient(360deg, #418CFF ' + value + '%, #ABB7CD ' + value + '%);')
  }

  //获取周边的index
  function getClosedIndex(index, off_lng, off_lat) {
    var lngNo = $scope.computeData.dataS[index].lngNo - 0;
    var latNo = $scope.computeData.dataS[index].latNo - 0;
    var reIndex = (lngNo + off_lng) + '-' + (latNo + off_lat);
    return $scope.computeData.relativeS[reIndex];
  }


  // $.getJSON('../data/street.json', function (resp){
  //   points = resp.geometries;
  //   var url = 'http://localhost:3000/api/roads';
  //   var num = 0;
  //   var insert = [];
  //   for(var i = 0; i < points.length; i++) {
  //     var point = points[i].coordinates;
  //     var data = {
  //       road_id: i,
  //       lng: point[0][0],
  //       lat: point[0][1], 
  //       a_lng: point[0][0],
  //       a_lat: point[0][1],
  //       b_lng: point[point.length - 1][0],
  //       b_lat: point[point.length - 1][1],
  //       remark: '',
  //       name: ''
  //     } 
  //     insert.push(data);  
  //     num ++;
  //     if(i % 300 == 0 && i > 0){
  //       $http({
  //         method: 'POST',
  //         url: url,
  //         data: insert
  //       }).success(function (response){
          
  //       });
  //       insert = [];
  //     }
  //   }
  //   $http({
  //     method: 'POST',
  //     url: url,
  //     data: insert
  //   }).success(function (response){
      
  //   });
  //   console.log('道路：' + num);
  // });
  // 
  $scope.chosenIt = []
  for(var i=0;i<8;i++){
    $scope.chosenIt.push(false)
/*    $scope.nineMonthMap.series[i+''] = {}*/
  }
  $scope.clickNine = function(d){
    if(d==-1){
        for(var i=0;i<8;i++){
          $scope.chosenIt[i] = false;
         delete $scope.nineMonthMap.series[i]
        }
        MapDiagram.drawMultipleLine('chart3', $scope.nineMonthMap);
    }else{
      
      var id = '';
      var name = ''
      if(d==0){
        id = getClosedIndex($scope.infoIndex,-1,-1)
        name = '1'
      }else if(d==1){
        id = getClosedIndex($scope.infoIndex,0,1)
        name = '2'
      }else if(d==2){
        id = getClosedIndex($scope.infoIndex,1,1)
        name = '3'
      }else if(d==3){
        id = getClosedIndex($scope.infoIndex,-1,0)
        name = '4'
      }else if(d==4){
        id = getClosedIndex($scope.infoIndex,1,0)
        name = '6'
      }else if(d==5){
        name = '7'
        id = getClosedIndex($scope.infoIndex,-1,-1)
      }else if(d==6){
        name = '8'
        id = getClosedIndex($scope.infoIndex,0,-1)
      }else if(d==7){
        name = '9'
        id = getClosedIndex($scope.infoIndex,1,-1)
      }
      if(id!=undefined){
        if($scope.chosenIt[d]==true){
          $scope.chosenIt[d] = false;
          delete $scope.nineMonthMap.series[d]
        }else{
          $scope.chosenIt[d] = true;
           var data = $scope.computeData.dataS[id].objects;
                 //九宫格图
          //年内月统计
          var tj = [0,0,0,0,0,0,0,0,0,0,0,0]
          for(var j=0;j<data.length;j++){
            var bjsj = new Date(data[j].BJSJ).getMonth()+1;
            if(bjsj-month+1>0){
              tj[bjsj-month]++;
            }else{
              tj[bjsj-month+12]++;
            }
          }
          $scope.nineMonthMap.series[d] = {
              name:name,
              color:'#2264FB',
              data:tj
          }
        }

        MapDiagram.drawMultipleLine('chart3', $scope.nineMonthMap);
      }

    }
    
   /* $scope.dataMap = MapAnalysis.countType($scope.infoData[checked].objects, $scope.qhour);*/

/*    MapDiagram.drawLine('chart3', $scope.dataMap);*/
  }
}